
#define SPDLOG_HEADER_ONLY
#define FMT_HEADER_ONLY
#include <spdlog/spdlog.h>
#include <spdlog/async.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include "spdlog/sinks/rotating_file_sink.h"

#include "process.hpp"
using namespace TinyProcessLib;

#include <windows.h>

class NoEndlineFormatter : public spdlog::formatter
{
public:
    void format(const spdlog::details::log_msg& msg, spdlog::memory_buf_t& dest) override
    {
        dest.append(msg.payload);
    }

    std::unique_ptr<formatter> clone() const override
    {
        return spdlog::details::make_unique<NoEndlineFormatter>();
    }
};

int  main()
{
    char JLinkFile[2048] = {0};
    GetPrivateProfileString("main", "JLinkFile", "JLink_x64.dll", JLinkFile, sizeof(JLinkFile), "./config.ini");
    char device[64] = {0};
    GetPrivateProfileString("main", "device", "GD32F205RG", device, sizeof(device) - 1, "./config.ini");

    uint32_t addr = GetPrivateProfileInt("main", "addr", 0x8000000, "./config.ini");
    uint32_t delay = GetPrivateProfileInt("main", "delay", 5000, "./config.ini");

    char cmd[2048] = {0};
    GetPrivateProfileString("main", "cmd", "cmd /C cd a.txt", cmd, sizeof(cmd), "./config.ini");
    char path[2048] = {0};
    GetPrivateProfileString("main", "path", "", path, sizeof(path), "./config.ini");

    UINT max_files     = GetPrivateProfileInt("main", "max_files", 2, "./config.ini");
    UINT max_file_size = GetPrivateProfileInt("main", "max_file_size", 5 * 1024 * 1024, "./config.ini");

    UINT max_cnt = GetPrivateProfileInt("main", "max_cnt", 3, "./config.ini");

    char logger_name[256] = {0};
    GetPrivateProfileString("main", "logger_name", "l.log", logger_name, sizeof(logger_name), "./config.ini");
    char pattern[256] = {0};
    GetPrivateProfileString("main", "pattern", ">: %v", pattern, sizeof(pattern), "./config.ini");

    std::vector<spdlog::sink_ptr> sinks;

    auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(logger_name, max_file_size, max_files);
    sinks.push_back(file_sink);

    auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    sinks.push_back(console_sink);

    spdlog::set_default_logger(std::make_shared<spdlog::logger>("multi-sink", begin(sinks), end(sinks)));

    spdlog::set_level(spdlog::level::info);
    spdlog::set_formatter(std::make_unique<NoEndlineFormatter>());
    //spdlog::set_pattern(pattern);

    do
    {
        spdlog::info("------------- [{}]\r\n", max_cnt);
        Process process2(
            cmd, path,
            [](const char* bytes, size_t n) {
                spdlog::info("{}", std::string(bytes, n));
            },
            [](const char* bytes, size_t n) {
                spdlog::error("{}", std::string(bytes, n));
            });
        process2.get_exit_status();
        Sleep(1000);
    } while (--max_cnt);
    return 0;
}
